﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.Xml;
using System.IO;
using System.Configuration;

namespace ViewMaker.Core.Wpf
{
    [Export(typeof(IXamlGenerator))]
    public class WpfXamlGenerator : IXamlGenerator
    {
        public static string Template { get; set; }

        const string defaultTemplate = 
@"<ContentControl 
    xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
    xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
    xmlns:system=""clr-namespace:System;assembly=mscorlib""
    IsTabStop=""False"">
    <ContentControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source=""/ViewMaker.Core;component/wpf/wpfgenericresource.xaml""/>
                <ResourceDictionary Source=""/ViewMaker.Core;component/wpf/wpferrorstyleresource.xaml""/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </ContentControl.Resources>                                   
</ContentControl>";

        static WpfXamlGenerator()
        {
            Template = ConfigurationManager.AppSettings["XamlTemplate"] ?? defaultTemplate;
        }

        public string Generate(ViewLayoutItem rootItem)
        {
            if (rootItem == null) throw new ArgumentNullException("rootItem");

            var xaml = CreateTemplate(rootItem);
            var xamlNode = new XamlNode(xaml.FirstChild);
            var cont = rootItem.CreateXaml(xamlNode).LastOrDefault();
            if (cont != null) xaml.FirstChild.AppendChild(cont.Node);
            return xamlNode.GetXamlCode();
        }

        private XmlDocument CreateTemplate(ViewLayoutItem rootItem)
        {
            var xamlString = Template;
            if (rootItem.Element.WindowSettings != null && !string.IsNullOrWhiteSpace(rootItem.Element.WindowSettings.Template))
            {
                xamlString = rootItem.Element.WindowSettings.Template;
            }
            return XamlNode.LoadXaml(xamlString).Node.OwnerDocument;
        }
    }

}
